package com.mokairui.symbol;

/**
 * @Description 符号表
 * @Author Mokairui
 * @Since 2022/3/27
 */
public class OrderSymbolTable<K extends Comparable<K>, V> {
    // 记录首节点
    private Node head;
    // 记录符号表中元素的个数
    private int N;

    public OrderSymbolTable() {
        this.head = new Node(null, null, null);
        N = 0;
    }
    
    // 获取符号表中键值对的个数
    public int size() {
        return N;
    }
    
    // 往符号表中插入键值对
    public void put(K key, V value) {
        // 定义两个Node变量, 分别记录当前节点和当前节点的上一个节点
        Node<K, V> curr = head.next;
        Node<K, V> pre = head;
        
        while (curr != null && key.compareTo(curr.key) > 0) {
            // 向下推移节点
            pre = curr;
            curr = curr.next;
        }
        
        // 如果当前节点curr的键和要插入的key一样, 则替换
        if (curr != null && key.compareTo(curr.key) == 0) {
            curr.value = value;
            return;
        }
        // 如果当前节点curr的键和要插入的key不一样,把新的节点插入到curr之前
        Node newNode = new Node(key, value, curr);
        pre.next = newNode;
        
        // 元素个数+1
        N++;
    }
    
    // 删除符号表中键为key的键值对
    public void delete(K key) {
        // 找到键为key的节点,把该节点从链表中删除
        Node<K, V> n = this.head;
        while (n.next != null) {
            // 判断n节点下一个节点的键是否为key, 如果是, 就删除该节点
            if (n.next.key.equals(key)) {
                n.next = n.next.next;
                N--;
                return;
            }
            n = n.next;
        }
    }
    
    // 从符号表中获取key对应的值
    public V get(K key) {
        // 找到键为key的节点
        Node<K, V> n = head;
        while (n.next != null) {
            if (n.next.key.equals(key)) {
                return n.next.value;
            }
            n = n.next;
        }
        return null;
    }

    private class Node<K, V> {
        private K key;
        private V value;
        private Node<K, V> next;

        public Node(K key, V value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }
}
